package com.zmc.admin.application.impl;

import com.zmc.admin.application.CommonService;
import com.zmc.admin.config.ServerConfig;
import com.zmc.common.config.SysConfig;
import com.zmc.common.utils.R;
import com.zmc.common.utils.file.FileUploadUtils;
import com.zmc.common.utils.file.FileUtils;
import com.zmc.common.constant.Constants;
import com.zmc.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：zmc
 * @Date：2024/10/10 12:37
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_COMMA = ",";

    public static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Override
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = SysConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @Override
    public R uploadFile(MultipartFile file) throws Exception {
        try {
            Map<String, Object> map = new HashMap<>();
            // 上传文件路径
            String filePath = SysConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            map.put("url", url);
            map.put("fileName", fileName);
            map.put("newFileName", FileUtils.getName(fileName));
            map.put("originalFilename", file.getOriginalFilename());
            return R.ok().put(map);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @Override
    public R uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            Map<String, Object> map = new HashMap<>();
            // 上传文件路径
            String filePath = SysConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            map.put("urls", StringUtils.join(urls, FILE_COMMA));
            map.put("fileNames", StringUtils.join(fileNames, FILE_COMMA));
            map.put("newFileNames", StringUtils.join(newFileNames, FILE_COMMA));
            map.put("originalFilenames", StringUtils.join(originalFilenames, FILE_COMMA));
            return R.ok().put(map);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @Override
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = SysConfig.PROFILE;
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
